import * as echarts from 'echarts/core';
import { TooltipComponent, LegendComponent } from 'echarts/components';
import { GraphChart } from 'echarts/charts';
import { LabelLayout } from 'echarts/features';
import { CanvasRenderer } from 'echarts/renderers';
import { useEffect, useRef } from 'react';
import getMockData from 'src/api/getMockData'
import './index.less'

echarts.use([
  TooltipComponent,
  LegendComponent,
  GraphChart,
  CanvasRenderer,
  LabelLayout
]);

function App() {
  const ref = useRef(null)
  const focusListRef = useRef([]);

  useEffect(() => {
    const myChart = echarts.init(ref.current);
    async function getDataAsync() {

      myChart.showLoading();
      const graph = await getMockData();
      const option = {
        tooltip: {},
        // legend: [{
        //   data: graph.categories.map((a) => a.name),
        //   selectedMode: false
        // }],
        animationDurationUpdate: 1500,
        animationEasingUpdate: 'quinticInOut',
        series: [{
          id: 'seriesid',
          layout: 'force',
          name: '影响力',
          type: 'graph',
          draggable: true, //是否可拖动
          animation: true,
          data: graph.nodes,
          edges: graph.edges,
          categories: graph.categories,
          edgeSymbol: ['none', 'arrow'],
          edgeSymbolSize: [4, 10],
          roam: true,
          label: {
            show: true,
            position: 'right',
            formatter: '{b}'
          },
          labelLayout: {
            hideOverlap: false,//隐藏
          },
          lineStyle: {
            color: 'source',
            curveness: 0.3,
            width: 0.5,
            opacity: 0.7
          },
          emphasis: {
            color: "inherit",
            focus: 'adjacency',
            blurScope: "global",
            label: {
              position: 'right',
              show: true
            }
          },
          selectedMode: 'single',
          force: {
            edgeLength: [10, 50], //边缘长度
            repulsion: 200, //排斥力
            gravity: 0, //重力
          },
        }]
      };


      myChart.on('mouseover', { dataType: 'node' }, function (e) {

        const id = e.data.id;
        const idSet = new Set();
        const linkData = graph.edges.filter(item => item.source === id || item.target === id)
        linkData.forEach(item => {
          idSet.add(item.source)
          idSet.add(item.target)
        })
        const indexList = [...idSet].map(item => graph.nodes.findIndex(ele => ele.id === item))

        if (focusListRef.current.length > 0) {
          // 取消高亮
          myChart.dispatchAction({
            type: 'downplay',
            dataIndex: focusListRef.current,
          })
        }
        // 高亮当前节点
        myChart.dispatchAction({
          type: 'highlight',
          dataIndex: indexList,
        })
      })

      myChart.on('mouseout', function () {
        if (focusListRef.current.length > 0) {
          myChart.dispatchAction({
            type: 'highlight',
            dataIndex: focusListRef.current,
          })
        }
      });

      myChart.on('selectchanged', { dataType: 'node' }, function (e) {

        const { fromAction, selected } = e;
        if (fromAction === "select") {
          console.log('选择node', selected[0].dataIndex[0])
          const dataIndex = selected[0].dataIndex[0]
          const node = graph.nodes[dataIndex]
          const id = node.id;
          const idSet = new Set();
          // 有关系的数据id
          const linkData = graph.edges.filter(item => item.source === id || item.target === id)
          linkData.forEach(item => {
            idSet.add(item.source)
            idSet.add(item.target)
          })
          focusListRef.current = [...idSet].map(item => graph.nodes.findIndex(ele => ele.id === item))

          myChart.dispatchAction({
            type: 'highlight',
            dataIndex: focusListRef.current,
          })

        } else {
          console.log('取消选择node')
          if (focusListRef.current.length > 0) {
            focusListRef.current = [];
            myChart.dispatchAction({
              type: 'downplay',
              dataIndex: focusListRef.current,
            })
          }
        }
      });

      myChart.hideLoading();
      myChart.setOption(option);
    }
    getDataAsync()

    return () => {
      myChart.dispose()
    }
  }, [])
  return (
    <div className="demo-container" ref={ref} />
  );
}

export default App;
